﻿//时间格式化函数
function dateConvert(value) {
    var reg = new RegExp('/', 'g');
    var d = eval('new ' + value.replace(reg, ''));
    //return new Date(d).format('yyyy-MM-dd hh:mm:ss')
    return new Date(d).format('yyyy-MM-dd')
}

$(function () {
    //时间格式化
    Date.prototype.format = function (format) {
        /*
        * eg:format="yyyy-MM-dd hh:mm:ss";
        */
        if (!format) {
            format = "yyyy-MM-dd hh:mm:ss";
        }

        var o = {
            "M+": this.getMonth() + 1, // month
            "d+": this.getDate(), // day
            "h+": this.getHours(), // hour
            "m+": this.getMinutes(), // minute
            "s+": this.getSeconds(), // second
            "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
            "S": this.getMilliseconds()
            // millisecond
        };

        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    };

    $.extend($.fn.datagrid.methods, {
        addToolbarItem: function (jq, items) {
            return jq.each(function () {
                var dpanel = $(this).datagrid('getPanel');
                var toolbar = dpanel.children("div.datagrid-toolbar");
                if (!toolbar.length) {
                    toolbar = $("<div class=\"datagrid-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(dpanel);
                    $(this).datagrid('resize');
                }
                var tr = toolbar.find("tr");
                for (var i = 0; i < items.length; i++) {
                    var btn = items[i];
                    if (btn == "-") {
                        $("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr);
                    } else {
                        var td = $("<td></td>").appendTo(tr);
                        var b = $("<a href=\"javascript:void(0)\"></a>").appendTo(td);
                        b[0].onclick = eval(btn.handler || function () { });
                        b.linkbutton($.extend({}, btn, {
                            plain: true
                        }));
                    }
                }
            });
        },
        removeToolbarItem: function (jq, param) {
            return jq.each(function () {
                var dpanel = $(this).datagrid('getPanel');
                var toolbar = dpanel.children("div.datagrid-toolbar");
                var cbtn = null;
                if (typeof param == "number") {
                    cbtn = toolbar.find("td").eq(param).find('span.l-btn-text');
                } else if (typeof param == "string") {
                    cbtn = toolbar.find("span.l-btn-text:contains('" + param + "')");
                }
                if (cbtn && cbtn.length > 0) {
                    cbtn.closest('td').remove();
                    cbtn = null;
                }
            });
        }
    });

})

//弹出框
//显示自定义的Window
function showMyWindow(windowName, title, href, width, height, modal, maximizable, maximized) {
    $(windowName).window({
        title: title,
        width: width === undefined ? 680 : width,
        height: height === undefined ? 500 : height,
        content: '<iframe scrolling="yes" frameborder="0"  src="' + href + '" style="width:100%;height:98%;"></iframe>',
        //href: href === undefined ? null : href,
        modal: modal === undefined ? true : modal,  //是否模态窗口（默认为true）
        minimizable: false,
        maximizable: maximizable === undefined ? true : maximizable,
        maximized: maximized === undefined ? false : maximized,
        shadow: false,
        cache: false,
        closed: false,
        collapsible: true,
        resizable: false,
        loadingMessage: '正在加载数据，请稍等片刻...'
    });
}

//关闭窗体
function colseMyWindow(windowName) {
    $(windowName).window('close');
}

function PreviewGraph(container, model) {
    if (!mxClient.isBrowserSupported()) {
        mxUtils.error('Browser is not supported!', 200, false);
    }
    else {
        mxConstants.SHADOWCOLOR = '#808080';
        mxRectangleShape.prototype.crisp = true;
        var graph = new mxGraph(container);
        graph.setEnabled(false);
        var style = graph.getStylesheet().getDefaultVertexStyle();
        style[mxConstants.STYLE_FONTCOLOR] = '#000000';
        style[mxConstants.STYLE_GRADIENTCOLOR] = '#CDE0FF';
        style[mxConstants.STYLE_FONTSIZE] = '11';
        style[mxConstants.STYLE_SHADOW] = '1';
        style[mxConstants.STYLE_ROUNDED] = '1';
        style[mxConstants.STYLE_GLASS] = '1';

        style = graph.getStylesheet().getDefaultEdgeStyle();
        style[mxConstants.STYLE_ROUNDED] = true;

        var parent = graph.getDefaultParent();
        graph.getModel().beginUpdate();
        try {
            var vertexArr = new Array();
            for (var i = 0; i < model.lstWorkFlowNodeView.length; i++) {
                var style = model.lstWorkFlowNodeView[i].Shape + model.lstWorkFlowNodeView[i].NodeColor + "glass=1;shadow=1;";
                var vertex = graph.insertVertex(parent, null, model.lstWorkFlowNodeView[i].NodeName, model.lstWorkFlowNodeView[i].LocationX, model.lstWorkFlowNodeView[i].LocationY, model.lstWorkFlowNodeView[i].Width, model.lstWorkFlowNodeView[i].Height, style);
                vertexArr[model.lstWorkFlowNodeView[i].NodeCode] = vertex;
            }

            for (var i = 0; i < model.lstRemindersWorkFlowNodeView.length; i++) {
                var parentNode = vertexArr[model.lstRemindersWorkFlowNodeView[i].NodeCode];
                var vertex = graph.insertVertex(parent, null, model.lstRemindersWorkFlowNodeView[i].NodeName, model.lstRemindersWorkFlowNodeView[i].LocationX, model.lstRemindersWorkFlowNodeView[i].LocationY, 40, 20, "");
            }

            for (var i = 0; i < model.lstWorkFlowNodeLineView.length; i++) {
                var currentNodeCode = model.lstWorkFlowNodeLineView[i].NodeCode;
                var nextNodeCode = model.lstWorkFlowNodeLineView[i].NextNodeCode;
                var e = graph.insertEdge(parent, null, model.lstWorkFlowNodeLineView[i].LineTitle, vertexArr[currentNodeCode], vertexArr[nextNodeCode], model.lstWorkFlowNodeLineView[i].LineColor);
                if (model.lstWorkFlowNodeLineView[i].LinePointX != null && model.lstWorkFlowNodeLineView[i].LinePointY != null) {
                    e.geometry.points = [new mxPoint(model.lstWorkFlowNodeLineView[i].LinePointX, model.lstWorkFlowNodeLineView[i].LinePointY)];
                }
            }
        }
        finally {
            graph.getModel().endUpdate();
        }
    }
}

//合并表格
function mergeCellsByField(tableID, colList) {
    var ColArray = colList.split(",");
    var tTable = $("#" + tableID);
    var TableRowCnts = tTable.datagrid("getRows").length;
    var tmpA;
    var tmpB;
    var PerTxt = "";
    var CurTxt = "";
    var alertStr = "";
    for (j = ColArray.length - 1; j >= 0; j--) {
        PerTxt = "";
        tmpA = 1;
        tmpB = 0;

        for (i = 0; i <= TableRowCnts; i++) {
            if (i == TableRowCnts) {
                CurTxt = "";
            }
            else {
                CurTxt = tTable.datagrid("getRows")[i][ColArray[j]];
            }
            if (PerTxt == CurTxt) {
                tmpA += 1;
            }
            else {
                tmpB += tmpA;

                tTable.datagrid("mergeCells", {
                    index: i - tmpA,
                    field: ColArray[j],　　//合并字段
                    rowspan: tmpA,
                    colspan: null
                });
                //tTable.datagrid("mergeCells", { //根据ColArray[j]进行合并
                //    index: i - tmpA,
                //    field: "Ideparture",
                //    rowspan: tmpA,
                //    colspan: null
                //});

                tmpA = 1;
            }
            PerTxt = CurTxt;
        }
    }
}

//根据传入的字段顺序，分组合并表格
function mergeCellsGroupByField(tTable, colList, startRows, endRows) {
    if (colList !== "") {
        var colArray = colList.split(",");
        if (colArray.length > 0) {
            if (colArray.length > 1) {
                colList = colList.replace(colArray[0] + ",", "");
            }
            else {
                colList = colList.replace(colArray[0], "");
            }
            var PerTxt = tTable.datagrid("getRows")[startRows][colArray[0]];
            var CurTxt = "";
            var tmpA = 1;

            for (i = startRows; i < endRows; i++) {
                CurTxt = tTable.datagrid("getRows")[i][colArray[0]];
                if (PerTxt == CurTxt) {
                    if (i > startRows) {
                        tmpA += 1;
                    }
                    if (i == endRows - 1) {
                        tTable.datagrid("mergeCells", {
                            index: endRows - tmpA,
                            field: colArray[0],
                            rowspan: endRows,
                            colspan: null
                        });
                        mergeCellsGroupByField(tTable, colList, startRows, endRows);
                    }
                }
                else {
                    tTable.datagrid("mergeCells", {
                        index: i - tmpA,
                        field: colArray[0],
                        rowspan: tmpA,
                        colspan: null
                    });
                    mergeCellsGroupByField(tTable, colList, i - tmpA, i);
                }
                PerTxt = CurTxt;
            }
        }
    }
}

//合并列：现在只用于进度管理这个模块，有时间在将方法通用
function mergeColCells(tableID) {
    var tTable = $("#" + tableID);
    var TableRowCnts = tTable.datagrid("getRows").length;
    for (i = 0; i < TableRowCnts; i++) {
        var item = tTable.datagrid("getRows")[i];
        if (item.ParentStatisticsItemName == item.StatisticsItemName) {
            var rowspanMerge = 1;
            var itemNext = tTable.datagrid("getRows")[i + 1];
            if (itemNext != null)
            {
                if (item.ID == itemNext.ID)
                {
                    rowspanMerge = 2;
                }
            }

            tTable.datagrid("mergeCells", {
                index: i,
                field: 'ParentStatisticsItemName',　　//合并字段
                rowspan: rowspanMerge,
                colspan: 2
            });

            if (itemNext != null) {
                if (item.ID == itemNext.ID) {
                    i++;
                }
            }
        }
    }
}

//根据传入的字段顺序合并行
//function mergeRowCells(tTable, colList, startRows, endRows) {
//    if (colList !== "") {
//        var colArray = colList.split(",");

//        for (i = startRows; i < endRows; i++) {
//            var value = tTable.datagrid("getRows")[i][colArray[1]];
//            if (value == '') {
//                tTable.datagrid("mergeCells", {
//                    index: endRows - tmpA,
//                    field: colArray[0],
//                    rowspan: endRows,
//                    colspan: null
//                });
//            }
//        }
//    }
//}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function formatDateToHLine(date, spit, newSpit) {
    if (date == "") {
        return ""
    }
    else {
        var arr = date.split(" ");
        var newarr = arr[0].split(spit);
        return newDate = newarr[0] + newSpit + newarr[1] + newSpit + newarr[2];
    }
}

function compareDate(a, b, spit) {
    var arr = a.split(spit);
    var starttime = new Date(arr[0], arr[1], arr[2]);
    var starttimes = starttime.getTime();

    var arrs = b.split("-");
    var lktime = new Date(arrs[0], arrs[1], arrs[2]);
    var lktimes = lktime.getTime();

    if (starttimes >= lktimes) {
        return false;
    }
    else
        return true;

}

function dateInterval(a, b, spit) {
    var arr = a.split(spit);
    var starttime = new Date(arr[0], arr[1], arr[2]);
    var starttimes = starttime.getTime();

    var arrs = b.split("-");
    var lktime = new Date(arrs[0], arrs[1], arrs[2]);
    var lktimes = lktime.getTime();

    return parseInt((lktimes - starttimes) / (1000 * 60 * 60 * 24));

}